package com.ld.caodan.common;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;

import com.ld.caodan.entity.Article;
import com.ld.caodan.util.NumberUtils;
import com.ld.caodan.util.StringUtils;

/**
 * 内容加载
 * 
 * @author LD
 *
 * 下午03:40:56  2012-9-17
 */
public class ContentLoader {

	Map<String, Article> contentMap = null;
	
	public ContentLoader() {
		this.contentMap = new HashMap<String,  Article>();
	}
	
	public Article loadContent(final String url,final ContentCallBack back){
		if(contentMap.containsKey(url)){
			 Article reference = contentMap.get(url);
			if(reference!=null){
				Article article = reference;
				if(article!=null){
					return article;
				}
			}
		}
		final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				back.getContent(url, (String)msg.obj);
			}
		};
		new Thread(new Runnable() {
			@Override
			public synchronized void run() {
				Article article = requestUri(url);
				contentMap.put(url, article);
				Message message = handler.obtainMessage(0, article.getContent());
				handler.sendMessage(message);
			}
		}).start();
		return null;
	}
	public static final int timeOut = 10000;
	Article requestUri(String url){
		try {
			Document document = Jsoup.parse(new URL(url), timeOut);
			Elements elements = document.getElementsByAttributeValue("class",
					"article");
			Article article = new Article(elements.get(0));
			String ding_cai_count_Url = "http://www.caodan.cc/plus/digg_ajax.php?id="+article.getId();
			Document dingcaiDoc = Jsoup.parse(new URL(ding_cai_count_Url), timeOut);
			Elements docElements = dingcaiDoc.getElementsByAttributeValue("class", "digg_num");
			if(docElements!=null&&docElements.size()>0){
				article.setDing(Integer.parseInt(NumberUtils.getNum(docElements.get(0).text())));
				article.setCai(Integer.parseInt(NumberUtils.getNum(docElements.get(1).text())));
				System.out.println("顶--->"+article.getDing()+"踩--->"+article.getCai());
			}
			return article;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public interface ContentCallBack{
		void getContent(String url,String content);
	}
	
}
